import logging
import os
import re
import time
import allure
import pytest
import uiautomator2 as u2
from time import sleep
from common.decs import relations


class App:
    def __init__(self):
        self.relations={}
        self.driver=u2.connect_usb()
        self.package=''
        #切换成fastInput输入法
        self.driver.set_fastinput_ime(True)

    def dev_connect(self):
        '''
        链接设备
        :param name:设备名称
        :return:
        '''
        self.driver=u2.connect_usb()
        return self.driver
    def appstart(self,package=''):
        '''
        打开app
        :param package:app的包名
        :return:
        '''
        #打开app
        try:
            self.driver.app_start(package)
            self.driver.implicitly_wait(10)
            self.package=package
            self.sleep(1)
        except Exception as e:
            self.close(package)
            self.driver.app_start(package)
            self.driver.implicitly_wait(10)
        return self.package

    def __find_ele(self,locator=""):
        '''
        自动判断元素定位方法
        :param locator: 元素定位
        :return:
        '''
        #如果元素以com开头，就用id定位
        if locator.startswith("com"):
            return self.driver(resourceId=locator)
        #如果元素以//开头，就用xpath定位
        elif locator.startswith("//"):
            return self.driver.xpath(locator)
        #否则用text定位
        else:
            return self.driver(textContains=locator)
    def click(self,locator1='',locator2=''):
        '''
        点击操作
        :param locator:
        :return:
        # '''
        # try:
        #如果第二个元素存在，就用坐标点击
        if locator2:
            self.driver.click(float(locator1),float(locator2))
        #否则就用element点击
        else:
            ele=self.__find_ele(locator1)
            ele.click()
    def double_click(self,xy='',time=''):
        '''
        双击
        :param x:X坐标
        :param y:Y坐标
        :param time:双击时间间隔
        :return:
        '''
        xy=xy.split(",")
        x=xy[0]
        y=xy[1]
        x=float(x)
        y=float(y)
        time=float(time)
        self.driver.double_click(x,y,time)
        return
    def long_click(self,locator="",locator1=""):
        '''
        长按
        :param x:x坐标
        :param y: y坐标
        :param time: 长按时间
        :return:
        '''
        #如果第二个元素存在就按照坐标来长按
        if locator1:
            self.driver.long_click(float(locator),float(locator1),2)
        else:
            ele=self.__find_ele(locator)
            ele.long_click()
    def Swipe(self,params=""):
        '''
        滑动
        :param params: 滑动方向 up down right left
        :return:
        '''
        self.driver.swipe_ext(params)
    def Drag(self,x1,x2,y1,y2):
        if y2:
            x1=float(x1)
            x2=float(x2)
            y1=float(y1)
            self.driver.drag(x1,y1,x2,y2,0.1)
        else:
            x1 = float(x1)
            x2 = float(x2)
            y1 = float(y1)
            self.driver.drag(x1, y1, x2, y1, 0.1)
        # self.driver.drag(x1,y1,x2,y1,0.1)

    @relations
    def input(self,locator='',value=''):
        '''
        输入
        :param locator:
        :param value:
        :return:
        '''
        # try:
        #获取焦点
        # ele=self.__find_ele(locator)
        # ele.click()
        #self.driver.xpath(locator).click()
        self.click(locator)
        logging.info("输入："+value)
        #清楚原来输入框内的的文本
        self.driver.clear_text()
        #重新输入文本
        self.driver.send_keys(str(value),clear=True)
        # ele=self.__find_ele(locator)
        # ele.send_keys(value)
        print("输入："+value)
    def search(self):
        self.driver.press("enter")
    @relations
    def get_text(self,locator='',reg=""):
        '''获取文本信息'''
        ele=self.__find_ele(locator)
        info=ele.info
        #如果这个元素包含text文本信息
        if info["text"]:
            text=info["text"]
            if reg:
                text = re.findall(r'\d{14}', text)[0]
                self.relations[reg] = text
            else:
                #把文本信息存起来
                self.relations["text"]=text
            print(self.relations)
        else:
            text='不存在text'
            self.relations["text"] = text
        return self.relations

    #自定义存储关联信息
    def save_params(self,key='',value=''):
        try:
            if key.startswith("reg"):
                if value.startswith("//")or value.startswith("com"):
                    ele = self.__find_ele(value)
                    info = ele.info
                    value = info["text"]
                    value=re.findall(r'\d{14}', value)[0]
                else:
                    value=value
            else:
                if value.startswith("//") or value.startswith("com"):
                    ele = self.__find_ele(value)
                    info = ele.info
                    value = info["text"]
                else:
                    value = value
            self.relations[key]=value
            print(self.relations)
        except Exception as e:
            self.attachshoot()
            self.restart()
            pytest.fail()
        return self.relations
    def sleep(self,num):
        '''等待'''
        if type(num)==int:
            sleep(num)
        else:
            sleep(float(num))
    def close(self,package=''):
        self.sleep(1)
        self.driver.app_stop(package)
    def back(self,num=""):
        if num:
            for i in range(int(num)):
                self.driver.press("back")
        self.driver.press("back")

    def restart(self):
        # self.attachshoot()
        self.close(self.package)
        self.appstart(self.package)
        self.sleep(1)
        self.click("主站")
    @relations
    def assert_equal(self,exp_value='',locator=''):
        ele = self.__find_ele(locator)
        try:
            try:
                info = ele.info
                if info:
                    act_value=info["text"]
                    logging.info("预期文案："+exp_value)
                    logging.info("检查文案："+act_value)
                    # self.attachshoot()
                    # allure.attach(open(self.relations["picture_file"], 'rb').read(), 'Screenshot',
                    #               attachment_type=allure.attachment_type.PNG)
                else:
                    act_value="不存在元素"
                    logging.info("预期文案：" + exp_value)
                    logging.info("检查文案：" + act_value)
            except Exception as e:
                act_value = "不存在元素"
                logging.info("预期文案：" + exp_value)
                logging.info("检查文案：" + act_value)

            if act_value.__contains__(exp_value) or exp_value.__contains__(act_value):
                pass
            else:
                self.attachshoot()
                self.restart()
                pytest.fail()
        except Exception as e:
            self.attachshoot()
            self.restart()
            pytest.fail()
    def click_ass(self,locator1="",locator2="",locator3=""):
        #加购的元素
        ele1=self.__find_ele(locator1)
        #售罄弹窗关闭的元素
        ele2=self.__find_ele(locator2)
        #另一个加购的元素
        ele3=self.__find_ele(locator3)
        ele1.click()
        if ele2 or ele3:
            try:
                #关闭弹窗
                ele2.click()
                #另一个加购
                ele3.click()
            except Exception as e:
                #如果没有售罄的元素就pass
                pass
        else:
            pass

    def attachshoot(self):
        time_stamp = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time()))
        picture_file ='./ErrorImg/error{0}.png'.format(time_stamp)
        self.relations["picture_file"]=picture_file
        print(self.relations['picture_file'])
        self.driver.screenshot(picture_file)
        allure.attach(open(self.relations["picture_file"], 'rb').read(), 'Fail Screenshot',
                      attachment_type=allure.attachment_type.PNG)
        return picture_file



if __name__ == '__main__':
    os.system('rd /s/q ErrorImg')
    sleep(5)
    os.mkdir("ErrorImg")
    app=App()
    app.dev_connect()
    app.attachshoot()

    # app.dev_connect()
    # app.appstart('com.yishouapp.fumi')
    # app.save_params("账号",'13631258769')
    # app.click('//*[@text="主站"]')
    # app.sleep(1)
    # app.click('com.yishouapp.fumi:id/tv_one_key_login')
    # app.sleep(1)
    # app.click('密码登录')
    # app.sleep(1)
    # app.input('输入手机号码','{账号}')
    # app.input('输入密码','a11111')
    # app.click("com.yishouapp.fumi:id/cb_user_privacy")
    # app.click("确定")
    # app.sleep(2)
    # app.attachshoot()
    # try:
    #     app.click('//*[@resource-id="com.yishouapp.fumi:id/main_tab5"]/android.widget.ImageView[1]')
    # except Exception as e:
    #     app.driver.screenshot("error.png")
    # app.sleep(2)
    # time_stamp = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time()))
    # picture_file = os.path.join(os.getcwd(), '../lib/error/error{0}.png'.format(time_stamp))
    # app.attachshoot(picture_file)
